<template>
	<view class="page-content">
		<f-navbar title="订单列表"></f-navbar>
		<view class="page-content-main">
			<!-- <scrollList :list="list" :loadComplete="loadComplete" @pullUpLoad="pullUpLoad" ref="scrollList"> -->
			<view class="list-block" style="margin-top: 30rpx;">
				<view v-for="(item,index) in list" :key="index" @click="toDetails(item)">
					<!-- driverOrderStatus 0待签到  1待提交回执 2已完成 -->
					<view class="list-item">
						<view class="item-header flex align-center">
							<view class="flex-sub text-cut text-cut1">订单号：{{item.orderCode}}</view>
							<view>
								<text class="color2" v-if="item.driverOrderStatus==0">待签到</text>
								<text class="color3" v-else-if="item.driverOrderStatus==1">待提交回执</text>
								<text class="color3" v-else-if="item.driverOrderStatus==2">已完成</text>
							</view>
						</view>
						<view class="item-middle">
							<view class="flex align-start item-step">
								<view class="item-check"></view>
								<view class="flex-sub item-right">
									<!-- listParams.taskType -->
									<view class="item-title">
										<text>始发地</text>
										<text class="margin-left"
											v-if="listParams.taskType == '0'">{{item.emissionUnitName}}</text>
										<text class="margin-left"
											v-if="listParams.taskType == '1'">{{item.recycleBinName}}</text>
									</view>
									<view class="item-address" v-if="listParams.taskType == '0'">
										地址：{{item.emissionUnitAddress}}
									</view>
									<view class="item-address" v-if="listParams.taskType == '1'">
										地址：{{item.recycleBinAddress}}
									</view>
								</view>

								<view class="left-line"></view>
							</view>
							<view class="flex align-start item-step">
								<view class="item-check active"></view>
								<view class="flex-sub item-right">
									<view class="item-title">
										<text>目的地</text>
										<text class="margin-left"
											v-if="listParams.taskType == '0'">{{item.recycleBinName}}</text>
										<text class="margin-left"
											v-if="listParams.taskType == '1'">{{item.startingStationName}}</text>
									</view>
									<view class="item-address" v-if="listParams.taskType == '0'">
										地址：{{item.recycleBinAddress}}
									</view>
									<view class="item-address" v-if="listParams.taskType == '1'">
										地址：{{item.startingStationAddress}}
									</view>
									<view class="item-info">
										联系人：{{item.contact}} {{item.contactPhone}}
									</view>
								</view>
							</view>
						</view>
						<view class="item-bottom">
							<view class="item-info">派单时间：{{item.createTime}}</view>
							<slot name="moreInfo"></slot>
							<view class="option-box flex align-center justify-end" v-if="item.taskStatus != 2">
								<view style="display: flex;">
									<view class="margin-left" @click.stop="signIn(item)"
										v-if="item.driverOrderStatus==0">
										<u-button color="linear-gradient(83deg, #48B453 0%, #2C9F79 100%)"
											v-if="item.isDeviation"
											:customStyle="{width:'171rpx',height:'63rpx',fontSize:'28rpx',borderRadius:'50rpx'}">偏离签到
										</u-button>
										<u-button color="linear-gradient(83deg, #48B453 0%, #2C9F79 100%)" v-else
											:customStyle="{width:'171rpx',height:'63rpx',fontSize:'28rpx',borderRadius:'50rpx'}">签到
										</u-button>
									</view>
									<view class="margin-left" @click.stop="submitReceipt(item)"
										v-if="item.driverOrderStatus==1">
										<u-button color="linear-gradient(83deg, #48B453 0%, #2C9F79 100%)"
											:customStyle="{width:'213rpx',height:'63rpx',fontSize:'28rpx',borderRadius:'50rpx'}">提交回执单
										</u-button>
									</view>
									<!-- taskType:null, //任务类型：0收运订单、1运输订单 -->
									<view class="margin-left" @click.stop="scanCode(item)"
										v-if="listParams.taskType == '0' && item.driverOrderStatus < 2">
										<u-button color="linear-gradient(83deg, #48B453 0%, #2C9F79 100%)"
											:customStyle="{width:'213rpx',height:'63rpx',fontSize:'28rpx',borderRadius:'50rpx'}">扫码
										</u-button>
									</view>
									
									
								</view>
							</view>
						</view>
					</view>

				</view>
			</view>
			<!-- </scrollList> -->
		</view>
		<!-- <screenModal ref="screenModal" @setScreenForm="setScreenForm"></screenModal> -->
	</view>
</template>
<script>
	import {
		getTaskList,
		confirmOrderReceipt,
		startDeparture,
		terminateTask,
		orderListByTask,
		check_in_range,
		notifyDeviceRun
	} from "@/api/task.js"
	import screenModal from "@/components/pageLayout/screenModal/warehousingScreenModal.vue"
	export default {
		components: {
			screenModal
		},
		data() {
			return {
				distanceNum: 0,
				currentPosition: {
					lat: 0, //纬度
					lng: 0, //经度
				},
				formatted_address:'',
				showSearch: false,
				listParams: {
					taskId: null,
				},
				list: [],
				loadComplete: true,
				optionItem: {}
			};
		},
		onPageScroll(e) {

		},
		onReady() {

		},
		onShow() {
			this.getSelfLocation()
			// this.check_in_range()
			// this.getList()
		},
		onLoad(option) {
			this.listParams = option
		},
		methods: {
			check_in_range() {
				check_in_range().then(res => {
					this.distanceNum = res.data || 0;
					this.getList()
				})
			},
			//获取当前位置经纬度
			getSelfLocation() {
				let location = {
					lat: 0, //维度
					lng: 0, //经度
				}
				let that = this
				uni.getLocation({
					type: 'gcj02', // 使用国标坐标系
					isHighAccuracy: true, // 高精度定位，会调用gps获取高精度坐标
					success(res) {
						console.log('定位位置',res);
						location.lat = res.latitude
						location.lng = res.longitude,
						that.currentPosition = location;
						// console.log(that.currentPosition);
						that.getFormattedAddress(location.lat,location.lng)
						that.check_in_range()
					},
					fail(err) {
						uni.$u.toast('请在设置中开启定位权限！');
						console.log('定位失败',err);
						that.check_in_range()

					}
				})
				// return new Promise((resolve, reject) => {
				// 	uni.getLocation({
				// 		type: 'gcj02', // 使用国标坐标系
				// 		isHighAccuracy: true, // 高精度定位，会调用gps获取高精度坐标
				// 		success(res) {
				// 			location.lat = res.latitude
				// 			location.lng = res.longitude,
				// 			resolve(location);
				// 		},
				// 		fail(err) {
				// 			reject(location);
				// 		}
				// 	})
				// })
			},
			getFormattedAddress(latitude, longitude){
				const location =   `${longitude},${latitude}`
				const key = '26b2ecf002ebe30ce54bfa3100e0dfc6'
				let that = this
				uni.request({
				  url: `https://restapi.amap.com/v3/geocode/regeo?location=${location}&key=${key}`,
				  success: (res) => {
					  // console.log('当前定位数据获取成功:', res);
					 const data = res.data;
					 if (data.status === '1') {
					   console.log('当前定位数据获取成功:', data.regeocode);
					   that.formatted_address = data.regeocode.formatted_address
					 } else {
					   console.error('定位获取失败code:', data.info);
					 }
				  },
				})
			},
			calculateDistance(lat1, lon1) {
				const res = this.currentPosition //await this.getSelfLocation()
				let lat2 = res.lat; //维度
				let lon2 = res.lng; //经度
				// 将经纬度从度转换为弧度
				const toRad = (value) => (value * Math.PI) / 180;
				const R = 6371; // 地球半径，单位千米
				const dLat = toRad(lat2 - lat1);
				const dLon = toRad(lon2 - lon1);
				const a =
					Math.sin(dLat / 2) * Math.sin(dLat / 2) +
					Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) *
					Math.sin(dLon / 2) * Math.sin(dLon / 2);
				const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
				const distance = R * c;
				return distance * 1000; // 返回距离，单位米
			},

			getList() {
				orderListByTask(this.listParams).then((res) => {
					res.data.forEach(item => {
						// 0 签到
						if (item.driverOrderStatus == 0) {
							console.log("目的地位置",item.latitude, item.longitude)
							let distance = this.calculateDistance(item.latitude, item.longitude)
							console.log('两点距离', distance);
							console.log('后台设置的距离', Number(this.distanceNum));
							let distanceNum = Number(this.distanceNum)
							if (distance > distanceNum) {
								// console.log(distance > distanceNum);
								item.isDeviation = true
							}
						}
					});
					this.list = res.data
					console.log(this.list);
					// this.$refs.scrollList.pullUpDone(!1)
					// if (this.listParams.pageNum == 1) {
					// 	this.list = res.data
					// 	this.loadComplete = !0
					// } else {
					// 	if (this.list.length == res.data.total) {
					// 		this.$refs.scrollList.pullUpDone(!0)
					// 	} else {
					// 		this.list = [...this.list, ...res.data.records]
					// 	}
					// }
				})
			},
			searchList() {
				this.listParams.pageNum = 1
				this.getList()
			},
			//订单详情
			toDetails(item) {
				// console.log(`./orderDetail?taskId=${this.listParams.taskId}&taskType=${this.listParams.taskType}&orderId=${item.id}`)
				this.goLink(
					`./orderDetail?taskId=${this.listParams.taskId}&taskType=${this.listParams.taskType}&orderId=${item.id}`
				)
			},
			/*签到*/
			signIn(item) {
				// 签到接口加个参数 isDeviation 是否偏离0否1是
				let isDeviation = item.isDeviation ? '1' : '0'
				this.goLink(
					`./signIn?taskId=${this.listParams.taskId}&orderId=${item.id}&taskType=${this.listParams.taskType}&isDeviation=${isDeviation}&position=${this.formatted_address}&lat=${this.currentPosition.lat}&lng=${this.currentPosition.lng}`
				)
			},
			/*提交回执单*/
			submitReceipt(item) {
				
				this.goLink(
					`./submitReceipt?taskId=${this.listParams.taskId}&taskType=${this.listParams.taskType}&orderId=${item.id}&startingStationType=${item.startingStationType}`
				)
			},
			scanCode(item){
				// 只允许通过相机扫码
				uni.scanCode({
					onlyFromCamera: true,
					success: function (res) {
						console.log('条码类型：' + res.scanType);
						console.log('条码内容：' + res.result);
						if(res.result){
							notifyDeviceRun({
								orderId:item.id,
								deviceCode:res.result,
							}).then(res => {
								console.log(res);
								uni.$u.toast('扫码成功！');
							})
						}else{
							uni.$u.toast('请重新扫描二维码！');
						}
					}
				});
			}
		},
	};
</script>
<style lang="scss" scoped>
	.page-content {
		// height: 100vh;
		// overflow: auto;
		// display: flex;
		// flex-direction: column;

		.search-block {
			padding: 32rpx;
			background: #f7f7f7;

			.search-input {
				height: 58rpx;
				background: #FFFFFF;
				border-radius: 50rpx;
				font-size: 28rpx;
				color: #CCCCCC;
				padding: 0 20rpx;
			}

			.screen-icon {
				width: 50rpx;
				height: 50rpx;
				margin-left: 24rpx;
			}
		}

		&-main {
			position: relative;
			flex: 1;
			overflow: hidden;

			.list-block {
				padding: 0 32rpx;
			}

		}
	}

	.list-item {
		margin-bottom: 32rpx;
		background: #ffffff;
		border-radius: 18rpx;
		padding: 0 32rpx;

		.item-header {
			padding: 20rpx 0;
			font-size: 30rpx;
			color: #000000;
			border-bottom: 1rpx solid #EFEFEF;

			.color1 {
				color: #FC880C;
			}

			.color2 {
				color: #138E57;
			}

			.color3 {
				color: #666668;
			}
		}

		.item-middle {
			padding: 30rpx 0;

			.item-step {
				position: relative;

				.left-line {
					height: calc(100% - 16rpx);
					width: 2rpx;
					background: #EFEFEF;
					position: absolute;
					left: 7rpx;
					top: 31rpx;
				}

				.item-check {
					width: 16rpx;
					height: 16rpx;
					border-radius: 50%;
					background: #138E57;
					margin-right: 20rpx;
					margin-top: 15rpx;

					&.active {
						background: #FC880C;
					}
				}

				.item-right {
					.item-title {
						font-size: 34rpx;
						font-weight: bold;
						color: #000000;
					}

					.item-address {
						margin-top: 16rpx;
						color: #666668;
						font-size: 30rpx;
						margin-bottom: 16rpx;
					}
				}
			}

		}

		.item-info {
			color: #666668;
			font-size: 30rpx;
		}

		.item-bottom {
			border-top: 1rpx solid #EFEFEF;
			padding: 20rpx 0 30rpx;

			.option-box {
				margin-top: 20rpx;
			}

			.item-info-sm {
				margin-top: 20rpx;
				color: #666668;
				font-size: 30rpx;
			}
		}
	}
</style>